package com.chinaisafe.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chinaisafe.base.common.enums.UserTypeEnum;
import com.chinaisafe.common.sdk.constant.UserConstant;
import com.chinaisafe.module.user.response.SysRoleRespVO;
import com.chinaisafe.user.entity.SysUser;
import com.chinaisafe.user.entity.SysUserRole;
import com.chinaisafe.user.mapper.SysRoleMenuMapper;
import com.chinaisafe.user.mapper.SysUserMapper;
import com.chinaisafe.user.mapper.SysUserRoleMapper;
import com.chinaisafe.user.service.SysUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaisafe.user.vo.request.SysUserRoleReqVO;
import com.chinaisafe.user.vo.response.SysUserRoleRespVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.chinaisafe.base.common.exception.BizException;
import com.chinaisafe.base.mybatisplus.constant.MybatisplusConstants;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaisafe.base.mybatisplus.util.MpQueryWrapperPageUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * SysUserRoleServiceImpl
 * Description：用户角色服务实现类
 *
 * @author xuefu.shu
 * @date 2024-07-13 16:53:56
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public IPage<SysUserRoleRespVO> getPageList(SysUserRoleReqVO sysUserRoleReqVO) {
        // 分页设置
        Page<SysUserRole> page = MpQueryWrapperPageUtil.buildWrapperPage(new Page<>(), sysUserRoleReqVO);
        // 查询条件构造
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getDeleted, MybatisplusConstants.LOGIC_NOT_DELETE_VALUE);
        return baseMapper.getPageList(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserRoleRespVO add(SysUserRoleReqVO sysUserRoleReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysUserRoleReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserRoleRespVO update(SysUserRoleReqVO sysUserRoleReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysUserRoleReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserRoleRespVO addOrUpdate(SysUserRoleReqVO sysUserRoleReqVO) {
        Long sysUserRoleId = sysUserRoleReqVO.getId();
        if (sysUserRoleId != null){
            // 编辑
            SysUserRole sysUserRole = baseMapper.selectById(sysUserRoleId);
            Optional.ofNullable(sysUserRole).orElseThrow(() -> BizException.build("未找到要修改的用户角色信息"));
        }
        SysUserRole sysUserRole2Save = sysUserRoleReqVO.convertToEntity();
        boolean success = this.saveOrUpdate(sysUserRole2Save);
        if (success) {
            return SysUserRoleRespVO.convertFromEntity(sysUserRole2Save);
        } else {
            BizException.throwException("操作失败，请刷新后重试");
        }
        return null;
    }

    @Override
    public SysUserRoleRespVO getDetailById(Long sysUserRoleId) {
        SysUserRole sysUserRole = baseMapper.selectById(sysUserRoleId);
        Optional.ofNullable(sysUserRole).orElseThrow(() -> BizException.build("未找到对应用户角色信息"));
        return SysUserRoleRespVO.convertFromEntity(sysUserRole);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Long[] sysUserRoleIds) {
        if (sysUserRoleIds.length > 0) {
            this.removeByIds(Arrays.asList(sysUserRoleIds));
        }
    }

    @Override
    public List<Long> queryUserRole(Long sysUserId) {
        SysUser sysUser = sysUserMapper.selectById(sysUserId);
        UserTypeEnum userTypeEnum = UserTypeEnum.getByCode(sysUser.getUserType());
        if (userTypeEnum == UserTypeEnum.ADMIN || userTypeEnum == UserTypeEnum.PLATFORM_ADMIN){
            //查询平台用户
            sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getSysAccountId, sysUser.getSysAccountId()).eq(SysUser::getTenancyCode, UserConstant.PLATFORM_TENANCY_CODE));
        }
        List<SysRoleRespVO> roles = this.baseMapper.queryByUserId(sysUser.getId());
        return roles.stream().map(SysRoleRespVO::getId).collect(Collectors.toList());
    }

    @Override
    public List<String> queryUserPermission(Long sysUserId) {
        List<Long> roles = queryUserRole(sysUserId);
        return sysRoleMenuMapper.queryUserPermission(roles);
    }
}
